package controller

import (
	"DouBan/bussiness"
	"DouBan/model"
	"github.com/gin-gonic/gin"
	"net/http"
)

func UserCaptcha() gin.HandlerFunc {
	return func(context *gin.Context) {
		content, uuid, err := bussiness.UserCaptcha()
		if err != nil {
			responseWithError(context, "UserCaptcha", http.StatusBadRequest, "请求验证码错误", err)
		} else {
			infoClaim := &model.InfoClaim{Uuid: uuid}
			context.Writer.Header().Del("set-cookie")
			context.SetCookie("token", infoClaim.GenerateJwtToken(), 1800, "", "", true, false)
			context.Writer.Header().Set("Content-Disposition", "attachment;filename=captcha.png")
			context.Data(http.StatusOK, "application/octet-stream", content)
		}
	}
}

func UserRegister() gin.HandlerFunc {
	return func(context *gin.Context) {
		userRegisterRequest := bussiness.UserRegisterRequest{}
		if err := context.BindJSON(&userRegisterRequest); err != nil {
			responseWithError(context, "userRegister", http.StatusBadRequest, "参数错误", err)
			return
		}
		infoClaim := getInfoClaim(context)
		msg, err := bussiness.UserRegister(infoClaim, userRegisterRequest)
		if err != nil {
			responseWithError(context, "userRegister", http.StatusBadRequest, msg, err)
		} else {
			responseWithSuccess(context, "userRegister", msg)
		}
	}
}

func UserLogin() gin.HandlerFunc {
	return func(context *gin.Context) {
		userLoginRequest := bussiness.UserLoginRequest{}
		if err := context.BindJSON(&userLoginRequest); err != nil {
			responseWithError(context, "userLogin", http.StatusBadRequest, "参数错误", err)
			return
		}
		infoClaim := getInfoClaim(context)
		msg, err := bussiness.UserLogin(infoClaim, userLoginRequest)
		if err != nil {
			responseWithError(context, "userLogin", http.StatusBadRequest, msg, err)
		} else {
			context.Writer.Header().Del("set-cookie")
			context.SetCookie("token", infoClaim.GenerateJwtToken(), 1800, "", "", true, false)
			responseWithSuccess(context, "userLogin", msg)
		}
	}
}
